<?php
	$groupid = checkUserGroup($_SESSION['username']);
	
	if (!isset($_GET['method'])) {
		if (checkGroupAdmin($groupid, $_SESSION['username'])) {
			echo "<p>Would you like to add a user via their <a href=\"?adduser=y&method=username\">Username</a> or <a href=\"?adduser=y&method=email\">Email Address</a>?</p>";
		}
		else {
			echo "<p>You must be an Admin of your Flatshare Group to invite new members.</p>"; 
		}
	}
	else {
		if ($_GET['method'] == "username") {
			if (isset($_GET['username'])) {
				$username = $_POST['username'];
				if (checkUser($username)) {
					if (checkUserGroup($username) == 0) {
						$result = inviteUser($groupid, $username, $_SESSION['username']);
						if ($result) {
							echo "<p>The user has been invited to the Flatshare Group and will appear in the group when they have accepted the invitation.</p>";
						}
						else {
							echo "<p>The user could not be invited to the Flatshare Group because an invitation is already pending.</p>";
						}
					}
					else {
						echo "<p>The user you have entered is already a member of a Flatshare Group.</p>";
					}
				}
				else {
					echo "<p>The username \"" . $username . "\" was not found. Please try again.";
					include("flatshare_php/group_adduser_form_username.php");
				}
			}
			else {
				include("flatshare_php/group_adduser_form_username.php");
			}
		}
		else if ($_GET['method'] == "email") {
			if (isset($_GET['email'])) {
				$username = findUserFromEmail($_POST['email']);
				if (!$username) {
					echo "<p>The email address \"" . $_POST['email'] . "\" was not found. Please try again.";
					include("flatshare_php/group_adduser_form_email.php");
				}
				else {
					if (checkUserGroup($username) == 0) {
						$result = inviteUser($groupid, $username, $_SESSION['username']);
						if ($result) {
							echo "<p>The user has been invited to the Flatshare Group and will appear in the group when they have accepted the invitation.</p>";
						}
						else {
							echo "<p>The user could not be invited to the Flatshare Group because an invitation is already pending.</p>";
						}
					}
					else {
						echo "<p>The user you have entered is already a member of a Flatshare Group.</p>";
					}
				}
			}
			else {
				include("flatshare_php/group_adduser_form_email.php");
			}
		}
	}
?>